package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.Logs;
import com.jwm.power.model.entity.Users;
import com.jwm.power.model.entity.XsfwCusarchive;
import com.jwm.power.model.excel.ExcelCusarchive;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.LogsRepository;
import com.jwm.power.repository.XsfwCusarchiveRepository;
import com.jwm.power.service.ExcelService;
import com.jwm.power.util.Ut;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLDecoder;
import java.util.*;

@Service
@Transactional
public class ExcelServiceImpl implements ExcelService {
    @Autowired
    private LogsRepository logsRepository;
    @Autowired
    private XsfwCusarchiveRepository xsfwCusarchiveRepository;

    //    导入Excel
    @Override
    public ResponseData ExcelImport(HttpServletRequest request) {
        try {
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");

            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            MultipartFile file = mr.getFile("myfile");

            if (file == null) {
                return new ResponseData(EnumResult.WORK_FAIL_NULLFILE, null);
            }
            // 获取原始文件名
            String fileName = file.getOriginalFilename();
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if (!suffixName.toLowerCase().contains("xls")) {
                return new ResponseData(EnumResult.WORK_FAIL_FILETYPE, null);
            }

            String content = "";
            switch (dataType) {
                case "pricing":
                    break;

            }
            //  添加日志
            Logs log = Ut.SaveLog("exprot", dataType, EnumOperate.IMPORT, users);     //  添加日志
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            //  手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  导出
    @Override
    public ResponseData ExcelExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            //实现excel写的操作
            //1 设置写入文件夹地址和excel文件名称
            String serverPath = URLDecoder.decode(ResourceUtils.getURL("").getPath(), "UTF-8");
            String fileUrl = serverPath + "heatdata/upload/" + Ut.getDataNow();
            File file = new File(fileUrl);
            //  如果文件夹不存在则创建
            if (!file.exists() && !file.isDirectory()) {
                file.mkdir();
            }
            String fName = "";
            switch (dataType) {
                case "cus": //  客户档案导出
                    exportCusarchive(fileUrl, fName, users);
                    break;
            }


            //  添加日志
            Logs log = Ut.SaveLog("exprot", dataType, EnumOperate.EXPORT, users);     //  添加日志
            logsRepository.save(log);
            //  返回用户数据
            Map<String, Object> uMap = new HashMap<>();
            uMap.put("fileUrl", "/upload/" + Ut.getDataNow() + "/" + fName + Ut.getDataNow() + ".xls");
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            //  手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  面试人员信息
    public void exportCusarchive(String fileUrl, String fName, Users users) {

        String fileName = fileUrl + "/" + fName + Ut.getDataNow() + ".xls";
        Optional<XsfwCusarchive> xsfwCusarchive = xsfwCusarchiveRepository.findById(15517);

        List<ExcelCusarchive> excelIntervieweeinfoList = new ArrayList<>();

        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setWrapped(true);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        // 表写入
        ExcelWriter writer = EasyExcel.write(fileName, ExcelCusarchive.class).registerWriteHandler(horizontalCellStyleStrategy).build();

        WriteSheet sheet = EasyExcel.writerSheet(0, "客户档案").build();
        writer.write(excelIntervieweeinfoList, sheet);

        // 关闭流
        writer.finish();
    }
}
